package com.mediacloud.app.newsmodule.activity


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.utils.SystemServiceManager

@SuppressLint("SetJavaScriptEnabled", "ObsoleteSdkInt")
open class LWebView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    WebView(context, attrs, defStyleAttr) {
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null)

    var maxHeight = 0

    init {

        webChromeClient = MyWebChromeClient(context, this)
        webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
              //  autoImgWidth()
            }
        }
        val mWebSettings = settings
        mWebSettings.javaScriptEnabled = true
        mWebSettings.setSupportZoom(true)
        mWebSettings.builtInZoomControls = false
        mWebSettings.savePassword = false
        if (checkNetwork(context)) {
            //根据cache-control获取数据。
            mWebSettings.cacheMode = WebSettings.LOAD_DEFAULT
        } else {
            //没网，则从本地获取，即离线加载
            mWebSettings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        }
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> {
                //适配5.0不允许http和https混合使用情况
                mWebSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                setLayerType(View.LAYER_TYPE_HARDWARE, null)
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT -> {
                setLayerType(View.LAYER_TYPE_HARDWARE, null)
            }
            Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT -> {
                setLayerType(View.LAYER_TYPE_SOFTWARE, null)
            }
        }
        mWebSettings.textZoom = 100
        mWebSettings.databaseEnabled = true
        if (Build.VERSION.SDK_INT >= 33){
            mWebSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        }else{
            mWebSettings.setAppCacheEnabled(true)
        }
        mWebSettings.loadsImagesAutomatically = true
        mWebSettings.setSupportMultipleWindows(false)
        // 是否阻塞加载网络图片  协议http or https
        mWebSettings.blockNetworkImage = false
        // 允许加载本地文件html  file协议
        mWebSettings.allowFileAccess = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            // 通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
            mWebSettings.allowFileAccessFromFileURLs = false
            // 允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源
            mWebSettings.allowUniversalAccessFromFileURLs = false
        }
        mWebSettings.javaScriptCanOpenWindowsAutomatically = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            mWebSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        } else {
            mWebSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
        }
        mWebSettings.loadWithOverviewMode = false
        mWebSettings.useWideViewPort = false
        mWebSettings.domStorageEnabled = true
        mWebSettings.setNeedInitialFocus(true)
        mWebSettings.defaultTextEncodingName = "utf-8"//设置编码格式
        mWebSettings.defaultFontSize = 16
        mWebSettings.minimumFontSize = 12//设置 WebView 支持的最小字体大小，默认为 8
        mWebSettings.setGeolocationEnabled(true)
        val dir: String = context.cacheDir.absolutePath
        //设置数据库路径  api19 已经废弃,这里只针对 webkit 起作用
        mWebSettings.setGeolocationDatabasePath(dir)
        mWebSettings.databasePath = dir
        if (Build.VERSION.SDK_INT < 33) {
            mWebSettings.setAppCachePath(dir)
            //缓存文件最大值
            mWebSettings.setAppCacheMaxSize(Long.MAX_VALUE)
        }

    }

    fun autoImgWidth() {

        val js = "javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{" +
                "var img = objs[i]; " +
                "img.style.maxWidth = '100%'; " +
                "img.style.height = 'auto'; " +
                //  "img.style.margin = '0 auto'; " +
                "}" +
                "})()"
        Log.w("autoImgWidth", js)
        loadUrl(js)
    }

    private fun checkNetwork(context: Context): Boolean {
        @SuppressLint("MissingPermission") val info = SystemServiceManager.getConnectivityManager(context).activeNetworkInfo
        return info != null && info.isConnected
    }


    internal class MyWebChromeClient(val context: Context, val webview: WebView) : WebChromeClient() {
        private var parentView: ViewGroup? = null

        private var myView: View? = null

        // 全屏
        override fun onShowCustomView(view: View, callback: CustomViewCallback) {
            super.onShowCustomView(view, callback)
            try {
                myView = view
                parentView = webview.parent as ViewGroup
                parentView?.removeView(webview)
                // 设置背景色为黑色
                view.setBackgroundColor(Color.BLACK)
                if (context is Activity) {
                    val contentContainer = context.findViewById<ViewGroup>(android.R.id.content)
                    context.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                    context.window.setFlags(
                        WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN
                    );
                    contentContainer.addView(view)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }


        }

        // 退出全屏
        override fun onHideCustomView() {
            super.onHideCustomView()
            try {
                parentView?.let {
                    if (context is Activity) {
                        val contentContainer = context.findViewById<ViewGroup>(android.R.id.content)
                        context.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
                        val attrs = context.window.attributes
                        attrs.flags = attrs.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN.inv()
                        context.window.attributes = attrs;
                        context.window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
                        contentContainer.removeView(myView)
                    }
                    it.addView(webview)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (maxHeight > 0 && MeasureSpec.getSize(heightMeasureSpec) > maxHeight) {
            setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), maxHeight)
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }
    }
}